package com.buba.personnel.controller;

import com.buba.personnel.service.DepartInfoService;
import com.buba.personnel.service.UserInfoService;
import com.buba.personnel.service.UserStateService;
import com.buba.pojo.*;
import com.buba.utils.ExcelUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * 员工控制层
 */
@RestController
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DepartInfoService departInfoService;
    @Autowired
    private UserStateService userStateService;

    @RequestMapping("/selUserInfo")
    public Pagination<UserInfo> selUserInfo(@RequestParam Map<String, Object> map) {
        Pagination<UserInfo> pagination = new Pagination<>(Integer.parseInt(map.get("page").toString()), Integer.parseInt(map.get("limit").toString()));
        //查询总条数 要带上查询条件
        long count = userInfoService.selUserInfoCount(map);
        pagination.setCount(count);
        map.put("index", pagination.getIndex());
        map.put("limit", pagination.getLimit());

        //查询当前页数据
        List<UserInfo> list = userInfoService.selUserInfo(map);
        pagination.setList(list);
        return pagination;

    }

    /**
     * 删除员工
     *
     * @param userInfoIds
     * @return
     */
    @RequestMapping("/delUserInfo")
    public Message delUserInfo(String userInfoIds) {
        System.out.println(userInfoIds);
        long count = userInfoService.delUserInfo(userInfoIds.split(","));
        return new Message(1, "删除了" + count + "条数据");
    }


    /**
     * 导出员工信息
     */
    @RequestMapping("/exportUserInfo")
    public void exportUserInfo(HttpServletResponse response) throws IOException, IllegalAccessException {
        //查询所有的员工信息
        List<UserInfo> list = userInfoService.selUserInfoAll();
        //调用excel工具类的导出功能
        new ExcelUtils<UserInfo>().export(list, response, UserInfo.class, "员工表");



//        //XSSFWorkbook 新版  poi提供的excel操作提供的
//        //HSSFWorkbook旧版
//        XSSFWorkbook workbook = new XSSFWorkbook();
//        //创建Sheet页
//        XSSFSheet sheet = workbook.createSheet();
//        //在页里创建行
//        XSSFRow row = sheet.createRow(0);
//        //在行里创建单元格
//        row.createCell(0).setCellValue("id");
//        row.createCell(1).setCellValue("名字");
//        row.createCell(2).setCellValue("部门");
//        row.createCell(3).setCellValue("性别");
//        row.createCell(4).setCellValue("角色");
//        row.createCell(5).setCellValue("状态");
//
//
//        //向excel中写入数据
//        int index = 1;
//        for (UserInfo userInfo:list){
//            XSSFRow row2 = sheet.createRow(index++);
//            row2.createCell(0).setCellValue(userInfo.getUserId());
//            row2.createCell(1).setCellValue(userInfo.getUserName());
//            row2.createCell(2).setCellValue(userInfo.getDepartInfo().getDepartName());
//            row2.createCell(3).setCellValue(userInfo.getGender() == 1 ? "男" : "女");
//            row2.createCell(4).setCellValue(userInfo.getRoleId());
//            row2.createCell(5).setCellValue(userInfo.getUserState().getUserStateName());
//        }
//        //将excel返回给浏览器下载
//        OutputStream outputStream = response.getOutputStream();
//        response.reset();
//        response.setHeader("Content-disponsition","attachment; filename=userInfo.xlsx");
//        response.setContentType("application/msexcel");
//        workbook.write(outputStream);
//        outputStream.close();
    }
    @RequestMapping("/importUserInfo")
    public Message importUserInfo(@RequestPart("upFile") MultipartFile multipartFile) throws IOException {
        if (!multipartFile.getOriginalFilename().endsWith(".xlsx")){
            return new Message(500,"非Excel文件");
        }
//        System.out.println(multipartFile.getOriginalFilename().endsWith(".xlsx"));

        //存储excel读取的员工信息
        List<UserInfo> list = new ArrayList<>();
        XSSFWorkbook workbook = new XSSFWorkbook(multipartFile.getInputStream());
        //获取第一页的数据
        XSSFSheet sheet = workbook.getSheetAt(0);

        //获取总行数
      int rowTotal = sheet.getLastRowNum();
      //遍历读取每行
      for (int i =1 ;i <= rowTotal; i++){
          XSSFRow row = sheet.getRow(i);
          UserInfo userInfo = new UserInfo();
          userInfo.setUserId(row.getCell(0).getStringCellValue());
          userInfo.setUserName(row.getCell(1).getStringCellValue());
          Cell genderCell = row.getCell(2);
          if(genderCell.getCellType()== CellType.NUMERIC){
              double gender=genderCell.getNumericCellValue();
              userInfo.setGender((int)gender);
          }else{
              userInfo.setGender(Integer.parseInt(genderCell.getStringCellValue()));
          }
          userInfo.setDepartInfoName(row.getCell(3).getStringCellValue());
          userInfo.setUserStateName(row.getCell(4).getStringCellValue());

          //将该对象装入集合中
          list.add(userInfo);
      }
      //部门、状态的id
         List<DepartInfo> departInfos = departInfoService.selDepartInfo();
       List<UserState> userStates = userStateService.selUserState();

      list.forEach(userInfo -> {
          //给员工赋值对应的部门id
          for (DepartInfo d:departInfos) {
              if (userInfo.getDepartInfoName().equals(d.getDepartName())){
                  userInfo.setDepartId(d.getDepartId());
                  break;
              }
          }
          //给员工赋值对应的状态id
          for (UserState u : userStates){
              if (userInfo.getUserStateName().equals(u.getUserStateName())){
                  userInfo.setUserStateId(u.getUserStateId());
                  break;
              }
          }
      });
      long count =  userInfoService.addUserInfoAll(list);
      return new Message(1,"添加了" + count + "条数据");
    }
}
